package com.example.chatroom.api;


import com.example.chatroom.model.User;
import com.example.chatroom.mapper.UserMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserAPI {
    @Resource
    private UserMapper userMapper;

    @PostMapping("/login")
    @ResponseBody
    public Object login(String username, String password, HttpServletRequest request) {
        User user = userMapper.selectByName(username);
        if (user == null || !user.getPassword().equals(password)) {
            System.out.println("登陆失败! 用户名或密码错误!" + user);
            return new User();
        }
        // 验证成功, 创建会话
        HttpSession session = request.getSession(true);
        session.setAttribute("user", user);
        user.setPassword("");
        return user;
    }

    @PostMapping("/register")
    @ResponseBody
    public Object register(String username, String password) {
        User user = null;
        try {
            user = new User();
            user.setUsername(username);
            user.setPassword(password);
            int result = userMapper.insert(user);
            System.out.println("注册 " + result + " 条数据");
            user.setPassword("");
        } catch (DuplicateKeyException e) {
            user = new User();
            System.out.println("注册失败 username = " + username);
        }
        return user;
    }

    @GetMapping("/userInfo")
    @ResponseBody
    public Object getUserInfo(HttpServletRequest req) {
        // 1.先从请求中获取会话
        HttpSession session = req.getSession(false);
        if (session == null) {
            // 会话不存在, 或者尚未登录, 返回一个 空对象
            System.out.println("[getUserInfo] 获取不到当前session对象!");
            return new User();
        }
        // 2.从会话中获取用户对象
        User user = (User) session.getAttribute("user");
        if  (user == null) {
            System.out.println("[getUserInfo] 获取不到当前user对象!");
            return new User();
        }
        user.setPassword("");
        return user;
    }
}
